package com.atguigu.eduorder.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.PageUtil;
import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.R;
import com.atguigu.eduorder.client.EduClient;
import com.atguigu.eduorder.entity.History;
import com.atguigu.eduorder.entity.Like;
import com.atguigu.eduorder.entity.Order;
import com.atguigu.eduorder.entity.query.OredrQuery;
import com.atguigu.eduorder.service.OrderService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author gengky
 * @since 2021-09-24
 */
@RestController
@RequestMapping("/eduorder/order")
//@CrossOrigin
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private EduClient eduClient;


    @ApiOperation("查询课程订单并绘制表格")
    @GetMapping("getCourseOrderChars/{begin}/{end}")
    public List<Order> getCourseOrderChars(@PathVariable(required = false) String begin,
                                           @PathVariable(required = false) String end){
        QueryWrapper<Order> wrapper=new QueryWrapper<>();
        //查询一定时间范围内
        if (!"null".equals(begin) && !"undefined".equals(begin) && !StringUtils.isEmpty(begin)){
            wrapper.ge("gmt_create",begin);
        }
        if (!"null".equals(end) && !"undefined".equals(begin) && !StringUtils.isEmpty(end)){
            wrapper.le("gmt_create", end);
        }
        List<Order> list = orderService.list(wrapper);
        return list;
    }

    @ApiOperation("根据会员ID查询购买课程")
    @GetMapping("getOrderByNumberId/{memberid}")
    public R getOrderByNumberId(@PathVariable String memberid){
        QueryWrapper<Order> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("member_id",memberid);
        queryWrapper.eq("status",1);
        List<Order> list = orderService.list(queryWrapper);
        return R.ok().data("orderCourses",list);
    }


    @GetMapping("getOrderListByNumberId/{memberid}")
    public List<Order> getOrderListByNumberId(@PathVariable String memberid){
        QueryWrapper<Order> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("member_id",memberid);
        queryWrapper.eq("status",1);
        List<Order> list = orderService.list(queryWrapper);
        return list;
    }
    /**
     * 生成订单的方法
     *
     * @return
     */
    @PostMapping("createOrder/{courseId}")
    public R createOrder(@PathVariable String courseId, HttpServletRequest request) {
        //创建订单，返回订单号
        String userId = JwtUtils.getMemberIdByJwtToken(request);
        String orderNo = orderService.createOrders(courseId, userId);



        return R.ok().data("orderId", orderNo);
    }

    /**
     * 查询所有的订单
     *
     * @return
     */
    @GetMapping("getAllOrder")
    public R getAllOrderInfo() {
        System.out.println("获取所有的订单信息");
        List<Order> list = orderService.list(null);
        return R.ok().data("items", list);
    }


    /**
     * 订单：条件查询带分页
     *
     * @return
     */
    @ApiOperation(value = "动态条件查询，分页用户列表")
    @PostMapping("pageOrderInfo/{current}/{limit}")
    public R pageOrderinfo(@PathVariable long current, @PathVariable long limit,
                           @RequestBody(required = false) OredrQuery oredrQuery) {
        //创建page对象
        Page<Order> pageOrder = new Page<>(current, limit);
        //构造条件
        QueryWrapper<Order> wrapper = new QueryWrapper<>();

        System.out.println("订单查询条件！！！");
        System.out.println(oredrQuery.toString());

        //订单号
        if (!StringUtils.isEmpty(oredrQuery.getOrderId())) {
            wrapper.like("order_no", oredrQuery.getOrderId());
        }
        //课程名称
        if (!StringUtils.isEmpty(oredrQuery.getCourseName())) {
            wrapper.like("course_title", oredrQuery.getCourseName());
        }
        //用户昵称
        if (!StringUtils.isEmpty(oredrQuery.getUserName())) {
            wrapper.like("nickname", oredrQuery.getUserName());
        }
        //订单创建时间
        if (!StringUtils.isEmpty(oredrQuery.getOrderdate())) {
            wrapper.like("gmt_create", oredrQuery.getOrderdate());
        }
        //支付状态
        if (!StringUtils.isEmpty(oredrQuery.getPayFlag())) {
            wrapper.like("status", oredrQuery.getPayFlag());
        }


        //排序
        wrapper.orderByDesc("gmt_create");
        //分页
        orderService.page(pageOrder, wrapper);

        List<Order> records = pageOrder.getRecords();
        long total = pageOrder.getTotal();

        return R.ok().data("total", total).data("list", records);


    }


    /**
     * 根据订单ID查询订单信息
     *
     * @param orderNo
     * @return
     */
    @GetMapping("getOrderInfo/{orderNo}")
    public R getOrderInfo(@PathVariable String orderNo) {

        System.out.println("根据订单ID查询订单信息");

        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no", orderNo);
        Order order = orderService.getOne(wrapper);
        return R.ok().data("item", order);
    }



    /**
     * 根据课程ID 和 用户ID 查询订单表中该课程是否购买
     */
    @GetMapping("isBuyCourse/{courseId}/{memberId}")
    public boolean isByCourse(@PathVariable("courseId") String courseId, @PathVariable("memberId") String memberId) {

        System.out.println("--------------------");
        System.out.println("isByCourse调用了");

        QueryWrapper<Order> wrapper = new QueryWrapper<>();


        if (!StringUtils.isEmpty(courseId)){
            wrapper.eq("course_id", courseId);
        }
        if (!StringUtils.isEmpty(memberId)){
            wrapper.eq("member_id", memberId);
        }

        wrapper.eq("status", 1);
        int count = orderService.count(wrapper);
        if (count > 0) {
            return true;
        } else {
            return false;
        }
    }

}

